package cxm.proj.xtalk;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Gallery.LayoutParams;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import cxm.lib.util.MyApplication;
import cxm.lib.util.MyLog;
import cxm.proj.xtalk.smack.ConnectManager;
import cxm.proj.xtalk.smack.ConnectTaskResultHandle;
import cxm.proj.xtalk.smack.Connector;
import cxm.proj.xtalk.smack.UserManager;

public class MainActivity extends FragmentActivity {
	private FragmentTabHost mTabHost = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
        // setup tabhost
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        TabWidget tabWidget = mTabHost.getTabWidget();
        android.view.ViewGroup.LayoutParams params = tabWidget.getLayoutParams();
        params.width = LayoutParams.WRAP_CONTENT;
        params.height = LayoutParams.WRAP_CONTENT;
        
        // add indicator
        // spec.setIndicator(view);
        LayoutInflater inflater = (LayoutInflater)this.getSystemService(           
                        Context.LAYOUT_INFLATER_SERVICE);                
        
        TabSpec spec = mTabHost.newTabSpec("Number");
        TextView text = (TextView)inflater.inflate(R.layout.main_tab_text, null);
        text.setText(R.string.call_buddy);
        text.setBackgroundColor(Color.parseColor("#604080d0"));
        spec.setIndicator(text);
        mTabHost.addTab(spec, NumberFragment.class, null);
        
        spec = mTabHost.newTabSpec("Number2");
        text = (TextView)inflater.inflate(R.layout.main_tab_text, null);
        text.setText(R.string.search_buddy);
        spec.setIndicator(text);
        mTabHost.addTab(spec, BuddyListFragment.class, null);
        
        // login fragment without showing its tab indicator
        spec = mTabHost.newTabSpec("Login");
        text = (TextView)inflater.inflate(R.layout.main_tab_text, null);
        // text.setText("abcd");
        text.setVisibility(View.INVISIBLE);
        spec.setIndicator(text);
        mTabHost.addTab(spec, LoginFragment.class, null);
        this.adjustLoginAppearance(true);
        
        // on tab changed
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override                                                          
            public void onTabChanged(String tabId) {
            	int tab = mTabHost.getCurrentTab();
            	for (int i = 0; i < mTabHost.getTabWidget().getTabCount(); i++) {
            		View enableView = mTabHost.getTabWidget().getChildAt(i).findViewById(
            				R.id.tab_title_text);
            		if (tab == i) {                                            
            			enableView.setBackgroundColor(Color.parseColor("#604080d0"));
            		} else {                                                   
            			enableView.setBackgroundColor(Color.parseColor("#00000000"));
            		}                                                          
            	}
            }
        });
	}
	
	private void adjustLoginAppearance(boolean isLogin) {
		if (isLogin) {
			mTabHost.getTabWidget().setVisibility(View.INVISIBLE);
			mTabHost.setCurrentTabByTag("Login");
		} else {
			mTabHost.getTabWidget().setVisibility(View.VISIBLE);
			if (mTabHost.getCurrentTab() == 2)
				mTabHost.setCurrentTab(0);
		}
	}
	
	private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			MyLog.Log(MyLog.Level.Error, "Receiver unknown intent: " + intent.getAction());

			if (!intent.getAction().equals(Connector.CONNECTION_EVENT)) {
				MyLog.Log(MyLog.Level.Error, "Receiver unknown intent: " + intent.getAction());
				return;
			}
			int eventType = intent.getExtras().getInt("type", 0);
			if (Connector.CONNECTION_ESTABLISHED == eventType) {
				// show tab indicator
				SharedPreferences prefs = PreferenceManager.
						getDefaultSharedPreferences(MainActivity.this);
				// save login account
				prefs.edit().putString("user", UserManager.getInstance().
						getLoginName()).commit();
				prefs.edit().putString("pass", UserManager.getInstance().
						getLoginPassword()).commit();
				
				// login, show real buddy tabs
				MainActivity.this.adjustLoginAppearance(false);
			} else if (Connector.CONNECTION_CLOSED_ERROR == eventType) {
				// setup login fragment
				MainActivity.this.adjustLoginAppearance(true);
			} else {
				MyLog.Log(MyLog.Level.Error, "Unknown event type: " + eventType);
			}
			
			/*
			// Log out, go to login activity
			UserManager.getInstance().Release();
			MainActivity.this.finish();
			
			Intent startIntent = new Intent(MainActivity.this, LoginActivity.class);
			MainActivity.this.startActivity(startIntent);
			*/
			
			// connection failed, show login fragment
		}
	};
	
	@Override
	public void onResume() {
		super.onResume();
		LocalBroadcastManager.getInstance(this).registerReceiver(this.messageReceiver,
				new IntentFilter(Connector.CONNECTION_EVENT));
		
		// check if not login, show login fragment
		if (UserManager.getInstance().getUser().isLogined()) {
			this.adjustLoginAppearance(false);
			return;
		}

		this.adjustLoginAppearance(true);
		// after connect, we try to login
		try {
			UserManager.getInstance().login(new ConnectTaskResultHandle() {
				@Override
				public void taskResultHandle(int result, Object tag) {
					if (0 == result) {
						MyLog.Log(MyLog.Level.Info, "User login success");
						// do nothing, process in broadcast receiver
					} else {
						MyLog.Log(MyLog.Level.Error, "Cannot login: " + result);
						Toast.makeText(MyApplication.context, 
								"Cannot login: " + result, Toast.LENGTH_LONG).show();

						MainActivity.this.cleanupAfterLoginError();
					}
				}
			}, null);
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "Cannot login: " + e);
			Toast.makeText(MyApplication.context, "Login exceptioin: " + e,
					Toast.LENGTH_LONG).show();
			this.cleanupAfterLoginError();
		}
	}
	
	private void cleanupAfterLoginError() {
		// reset state
		UserManager.Release();
		ConnectManager.Release();
		// go back to login activity to reset account
		Intent intent = new Intent(MainActivity.this, LoginActivity.class);
		intent.putExtra("type", "LoginFail");
		MainActivity.this.startActivity(intent);
	}
	
	@Override
	
	public void onPause() {
		super.onPause();
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				this.messageReceiver);
	}
}
